package org.hepeng.workx.spring.cloud.netflix.zuul.route;

import com.google.common.net.InternetDomainName;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.Route;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author he peng
 */

@Slf4j
public class Level2DomainZuulRoutingRewriteMatch extends AbstractZuulRoutingRewriteMatch {

    public Level2DomainZuulRoutingRewriteMatch(HttpServletRequest request, String originalUri, List<Route> routes) {
        super(request, originalUri, routes);
    }

    @Override
    protected String getApplicationId() {
        return getLevel2DomainName();
    }

    private String getLevel2DomainName() {
        String name = "";
        try {
            String serverName = super.request.getServerName();
            if (InternetDomainName.isValid(serverName)) {
                InternetDomainName internetDomainName = InternetDomainName.from(super.request.getServerName());
                name = internetDomainName.parts().get(0);
                if (StringUtils.equals("www" , name)) {
                    return "";
                }
            }
            return name;
        } catch (Exception e) {
            log.error(e.getMessage() , e);
        }
        return name;
    }

    @Override
    protected boolean matchRoute(Route route, String appId) {
        if (StringUtils.isNotBlank(appId)
                && ! StringUtils.startsWithAny(super.originalUri
                , route.getPrefix() , super.zuulProperties.getServletPath())
                && StringUtils.endsWithIgnoreCase(route.getId() , appId)) {

            super.request.setAttribute(REWRITE_MATCH_CLASS_REQUEST_ATTR, this.getClass().getName());
            return true;
        }

        return false;
    }

}
